<template>
  <div class="container">
    <div class="button-box-top">
      <customButton  title="加工" theme="primary" size="medium" :disabled="strings.isNotBlank(form.busKey)" @click="handleProcess()"   help="进行加工锁库操作" />
      <customButton  title="撤销加工" theme="danger" size="medium" :disabled="strings.isBlank(form.id) || submitStatus != 0" @click="handleUnProcess()"   help="撤销当前加工单的加工操作，提交后才可以进行操作"/>
      <customButton  title="提交" theme="success" size="medium" :disabled="strings.isBlank(form.id) || submitStatus != 0" @click="handleSubmit()"    help="加工后才可以进行操作" />
      <customButton  title="提交并上架" theme="primary" size="medium" :disabled="strings.isBlank(form.id) || submitStatus != 0" @click="handleShelf"    help="提交并根据库存耗材设置自动上架，加工后才可以进行操作"/>
      <customButton  title="撤销提交" theme="danger" size="medium" :disabled="submitStatus != 1" @click="handleUnSubmit()"   help="撤销当前加工单的提交，提交后才可以进行操作"/>
      <customButton  title="刷新" theme="primary" size="medium" :disabled="cpIsSplit" @click="fetchData()"   help="拆分操作时，刷新加工明细"/>
      <customButton  title="打印标签" theme="default" size="medium" :disabled="submitStatus != 1" @click="handlePrint()"  help="打印当前所加工的标签"/>
      <customButton  title="重置表单" theme="default" size="medium" @click="handleReset()" help="还原用户操作"/>
      <span v-if="snMergeNew" class="tag-name" ><stong>合并后标签: </stong>{{snMergeNew}}</span>
      <span v-if="form.locationIdcode" class="tag-name" >
          <stong>目标货位: </stong>({{form.locationName}})，<stong>识别码: </stong>({{form.locationIdcode}})
      </span>
    </div>

    <div class="form-layout">
      <!--左侧导航-->
      <div class="nav-left">
        <customAnchor
          :itemList="[
            { name: 'box-base', title: '加工' },
            { name: 'box-old', title: '原包装' },
            { name: 'box-new', title: '新包装' },
            { name: 'box-dtl', title: '加工明细' },
          ]"
        />
      </div>

      <!--表单区域-->
      <div class="form-right" ref="formRight">
        <div id="box-base" class="box-title">加工</div>
        <customForm :data="form" ref="editForm" :rules="rules">
          <template #content>
            <customTooltip>
              <template #title>
                选择库存或者扫描相关标签码
              </template>
              <template #content>
                <FortenScan
                  ref="txtScan"
                  propPlaceholder="扫描标签码"
                  @after-scan="barCodeScan"
                  propType="uniqueCode"
                  style="width: 300px;margin-top: 10px;display: inline-block; margin-right: 5px"
                />
                <customButton
                title="选择库存"
                theme="primary"
                @click="utilSelect.stock(selectChangeStock, utils.getCurrentWarehouse().id, 0, true, true, '1')"
                  />
              </template>
            </customTooltip>
            <customFormItem label="加工类型" name="processType"
                            @change="changeType"
                            :parent="_self" :form="formOp"
                            :type="constCommon.formItemType.radio.name"
                            :config="{options: processTypeList, defaultValue: '1'}"
                            style="margin-top: 14px"
            />
            <customFormItem label="加工单号" name="busKey" :parent="_self" :form="form" disabled  style="margin-top: 14px"/>
            <div id="box-old" class="box-title">原包装</div>
            <customFormItem
              label="供应商"
              name="supplierName"
              :parent="_self"
              :form="form"
              :readonly="true"
              :showSelectIcon="true"
              disabled
            />
            <customFormItem label="商品名称" name="matrName" :parent="_self" :form="form" disabled />
            <customFormItem label="商品规格" name="matrSpec" :parent="_self" :form="form" disabled  />
            <customFormItem label="货位" name="locationName" :parent="_self" :form="form" disabled  />
            <customFormItem label="SN码" name="sn" :parent="_self" :form="form" disabled  />
            <customFormItem label="包装单位" name="packageUnit" :parent="_self" :form="form" disabled  />
            <customFormItem label="批次" name="lot" :parent="_self" :form="form" disabled  />
            <customFormItem label="生产日期" name="mfgDate" :parent="_self" :form="form" disabled  />
            <customFormItem label="有效期" name="expDate" :parent="_self" :form="form" disabled  />
            <customFormItem label="单品数量" name="skuQty" :parent="_self" :form="form" disabled  />

          <div id="box-new" class="box-title">新包装</div>
          <customFormItem
          label="包装单位"
          name="packageProcess" :parent="_self" :form="form"
          :type="constCommon.formItemType.selectStatic.name"
          :config="{options: matrUnits, label: 'unit', value: 'unit'}"
          :disabled="strings.isNotBlank(form.busKey)"
          @change="matrUnitChange"
          :clearable="false"
            />
          <customFormItem label="单品数量" name="processRate" :parent="_self" :form="form" disabled  />
        </template>
      </customForm>

      <div id="box-dtl" class="box-title">加工明细</div>
      <!-- 拆分 -->
      <data-view ref="childProcessItem"
        v-show="cpIsSplit"
        propViewKey="wm_stock_process_item"
        :propFlowKey="propFlowKey"
        :propHideQueryButton="true"
        :propShowToolBar="true"
        :propHidePageSearch="true"
        :propAutoFetchData="false"
        @extra-button-click="handleExtraButtonClick"
        :propIsTdesign="true"
      />
       <!-- 合并 -->
      <data-view ref="childProcessStock"
        v-show="!cpIsSplit"
        propViewKey="wm_stock_process_stock"
        :propFlowKey="propFlowKey"
        :propPageSize="500"
        :propShowToolBar="true"
        :propHideQueryButton="true"
        :propHidePageSearch="true"
        :propAutoFetchData="false"
         @after-load="setCheckedRecores"
        @extra-button-click="handleExtraButtonClick"
        :propIsTdesign="true"
      />
    </div>
  </div>
</div>
</template>

<script>
import barcodeParse from '@/util/barcodeParse.js'
import customAnchor from '@/components/custom/form/customAnchor.vue'

export default {
  name: 'process',
  props: ['propFlowKey'],
  data() {
    return {
      form: {
        matrId: null,
        id: null,
      },
      formOp: {
        processType: "1"
      },
      txtScan: '',
      matrUnits: [],
      processTypeList: [
        {
          value: "1",
          label: '拆分',
        },
        {
          value: "2",
          label: '合并',
        }
      ],
      tipsTitle: '合并时选择的库存数量必须等于要加工的包装单位比率，否则会加工失败',

      //提交状态 -1：未扫描  0：未提交，1：已提交
      submitStatus: -1,
      //合并后标签
      snMergeNew: null,
      historyVisible: false, //显示历史加工单
      propSnArr: [],
      autoFlagCheck: false,
      // 校验规则
      rules: {
        packageProcess: [
          {
            required: true,
            message: '新包装必填',
            type: 'error',
            trigger: 'blur',
          }
        ]
      }
    }
  },
  components: {
    customAnchor,
  },

  computed: {
    cpProcessType() {
      return this.formOp.processType  //1 拆分 2 合并
    },

    // 是否是标签拆分
    cpIsSplit() {
      return this.cpProcessType == "1"
    },
  },
  mounted() {
    setTimeout(() => {
      this.fetchData()
    },500)
  },
  methods: {
    // 加载页面 初始化
    fetchData() {
      // 拆分
      this.$refs.childProcessItem && this.$refs.childProcessItem.setQueryWrapper(this.getChildItemQueryWrapper())
      // 合并
      this.$refs.childProcessStock && this.$refs.childProcessStock.setQueryWrapper(this.getChildStockQueryWrapper())
    },
    initData() {
      this.form = {}
      this.submitStatus = -1
      this.snMergeNew = null
      this.txtScan = ''
      this.$set(this.formOp, 'processType', "1")
    },
     //扫码SN或RFID
    async barCodeScan(txtScan) {
      this.snMergeNew = null
      this.submitStatus = -1
      const scan = txtScan || this.txtScan
      let codeType = barcodeParse.barCodeType(scan)
      // debugger
      console.log('processType---', this.cpProcessType)
      if (codeType == 'SN') {
        let params = {
          sn: scan,
          processType: this.cpProcessType
        }
        await this.$ajax.get('/wm/stock_process/barCodeScan', {params}).then(resp => {
          if (resp.code == 0) {
            if (resp.data) {
              this.form = global.utils.jsonClone(resp.data)
              this.getMatrUnits()
              this.fetchData()
            } else {
              this.utilMessage.error('扫码错误，SN/RFID不存在')
            }
          }
        })
      } else {
        this.utilMessage.error('扫码错误，SN/RFID格式不正确')
      }
    },
    selectChangeStock(row) {
      if (!row || !row.sn) {
        return false
      }
      this.txtScan = row.sn
      this.barCodeScan()
    },
    matrUnitChange(matrUnit) {
      let changeRate = this.matrUnits.filter(pu => pu.unit == matrUnit).map(pu => pu.rate)[0]
      this.$set(this.form, 'processRate', changeRate)
    },
    changeType() {
      this.form = {}
      this.submitStatus = -1
      this.snMergeNew = null
      this.txtScan = ''
      this.fetchData()
    },
    // 获取新包装列表
    getMatrUnits() {
      this.matrUnits = []
      if (!this.form.matrId) {
        return
      }
      let that = this
      this.$ajax.get('/base/matrUnit/getByMatr', {params: {matrId: this.form.matrId}}).then(resp => {
        if (resp.code == 0) {
          that.matrUnits = resp.data
          console.log('matrUnits----resp.data', that.matrUnits)
          //获取第一个小包装
          let packageUnit = resp.data.filter(unit => unit.unit == that.form.packageUnit)[0]

          that.matrUnits = resp.data.filter(unit => unit.unit != that.form.packageUnit) //排除当前包装单位
          if (that.matrUnits.length == 0) {
            this.submitStatus = -1
            this.utilMessage.warning('该耗材没有可用的包装单位')
            return
          }

          console.log('that.processType', that.cpProcessType)

          that.matrUnits = that.cpIsSplit ? that.matrUnits.filter(unit => unit.rate < packageUnit.rate).sort((a, b) => b.rate - a.rate)
            : that.matrUnits.filter(unit => unit.rate > packageUnit.rate).sort((a, b) => a.rate - b.rate)

          console.log('matrUnits----', that.matrUnits)

          if (that.matrUnits.length) {
            this.submitStatus = 0
            that.$set(this.form, 'packageProcess', this.matrUnits[0].unit)
            that.matrUnitChange(this.form.packageProcess)
            this.$set(this, 'matrUnits', that.matrUnits)
          } else {
            let typeName = this.cpIsSplit ? '拆分' : '合并'
            this.utilMessage.warning('该耗材没有可用的' + typeName + '单位,请到耗材界面维护相关单位')
            this.submitStatus = -1
          }
        }
      })
    },
    //默认不显示库存，必须选择某一条件后才显示
    getChildItemQueryWrapper() {
      if (!this.form.id) {
        return this.$newWrapper().ne(1, 1)
      }
      return this.$newWrapper().eq('processId', this.form.id)
    },
    getChildStockQueryWrapper() {
      if (!this.form.matrId || this.cpIsSplit) {
        this.autoFlagCheck = false
        return this.$newWrapper().ne(1, 1)
      }
      return this.$newWrapper().eq('matrId', this.form.matrId)
        .eq('warehouseId', this.utils.getCurrentWarehouse().id)
        .eq('packageUnit', this.form.packageUnit)
        .gt('skuQty', 0)
        .eq('lot', this.form.lot)
        .eq('expDate', this.form.expDate)
        .eq('flagOmoc', 0)
        .eq('lockQty', 0)
        .eq('packageQty', 1)
        .eq('supplierId', this.form.supplierId)
    },

    //历史加工单
    showProcessHistory() {
      this.historyVisible = true
    },

    // 加工 & 提交并上架
    handleProcess() {
      if (!this.form.stockId) {
        this.utilMessage.error('请先扫描需要加工的SN码包装')
        return
      }
      if (!this.form.packageProcess) {
        this.utilMessage.error('请先选择需要加工的新包装')
        return
      }
      this.$set(this.form, 'processType', this.cpProcessType)
      if (this.cpIsSplit) { // 拆分
        if (this.form.skuQty % this.form.processRate != 0) {
          this.utilMessage.error('新包装不能满足加工条件，必须得是整数倍的包装才可以')
          return
        }
        this.$set(this.form, 'processQty', this.form.skuQty / this.form.processRate)
        let formParam = this.utils.jsonClone(this.form)
        this.utilVue.loadShow(true)
        // formParam.skuQty = this.form.processRate
        this.$ajax.post('/wm/stock_process/process', formParam).then(resp => {
          if (resp.code == 0) {
            this.submitStatus = 0
            this.utilMessage.success(resp.msg)
            this.form.id = resp.data.id
            this.form.busKey = resp.data.busKey
            this.fetchData()
            this.utilVue.loadHide()
          }
        })
      } else { //合并
        let checkedRecords = this.$refs.childProcessStock.$refs.tbMain.getCheckboxRecords()
        if (!checkedRecords || !checkedRecords.length) {
          this.utilMessage.error('请先选择要加工的库存信息')
        }
        if (this.form.skuQty * checkedRecords.length != this.form.processRate) {
          this.utilMessage.error('不满足加工条件，选择耗材的数量必须等于新包装单位的规格数量才可以加工')
          return
        }

        let formParam = this.utils.jsonClone(this.form)
        // formParam.skuQty = this.form.processRate
        formParam.processQty = 1
        formParam.amount = this.form.amount * checkedRecords.length
        formParam.skuQty = this.form.skuQty * checkedRecords.length
        formParam.stocks = checkedRecords
        this.utilVue.loadShow(true)
        this.$ajax.post('/wm/stock_process/process', formParam).then(resp => {
          if (resp.code == 0) {
            this.utilMessage.success(resp.msg)
            this.form.id = resp.data.id
            this.form.busKey = resp.data.busKey
            this.form.amount = formParam.amount
            this.form.skuQty = formParam.skuQty
            this.utilVue.loadHide()
          }
        })
      }
    },
    handleProcessAndPrint() {
    },
    handlePrint() {
      //1 拆分，2合并
      if (this.cpIsSplit) {
        this.propSnArr = []
        this.$refs.childProcessItem.rows0.forEach(ob => this.propSnArr.push(ob.sn))
      } else {
        this.propSnArr = [this.snMergeNew]
      }
      global.utilPrint.openPrintLabel(null, null, this.propSnArr)
    },
    handleSubmit() { //提交
      if (!this.form.id) {
        this.utilMessage.error('请先进行加工操作')
        return
      }
      if (this.$refs.childProcessItem.getRows() == null) {
        this.utilMessage.error('请先进行加工操作')
        return
      }
      this.form.submitStatus = this.submitStatus
      this.form.processType = this.cpProcessType
      this.utilVue.loadShow(true)
      this.$ajax.post('/wm/stock_process/submit', this.form).then(resp => {
        if (resp.code == 0) {
          this.submitStatus = 1
          this.utilMessage.success(resp.msg)
          this.form.id = resp.data.id
          this.snMergeNew = null
          if (!this.cpIsSplit) {
            this.snMergeNew = resp.data.sn
            this.form.stockId = resp.data.stockId
          }
        }
        this.utilVue.loadHide()
      })
    },
    //上架
    handleShelf() {
      this.utilVue.loadShow(true)
      this.form.processType = this.cpProcessType
      this.form.submitStatus = this.submitStatus
      this.$ajax.post('/wm/stock_process/submitUp', this.form).then(resp => {
        if (resp.code == 0) {
          this.submitStatus = 1
          this.utilMessage.success(resp.msg)
          this.form.locationId = resp.data.locationId
          this.form.locationName = resp.data.locationName
          this.form.locationIdcode = resp.data.locationIdcode
          this.utilVue.loadHide()
          if (!this.cpIsSplit) {
            this.snMergeNew = resp.data.sn
            this.form.stockId = resp.data.stockId
          }
        }
        this.utilVue.loadHide()
      })
    },
    handleUnProcess() { //撤销加工
      this.utilVue.loadShow(true)
      this.$ajax.post('/wm/stock_process/un_process', this.form).then(resp => {
        if (resp.code == 0) {
          this.submitStatus = 0
          this.utilMessage.success(resp.msg)
          this.form = {}
          this.txtScan = resp.data.sn
          this.barCodeScan()
        }
        this.utilVue.loadHide()
      })
    },
    handleUnSubmit() { //撤销提交
      this.form.submitStatus = this.submitStatus
      this.form.processType = this.cpProcessType
      this.utilVue.loadShow(true)
      this.$ajax.post('/wm/stock_process/un_submit', this.form).then(resp => {
        if (resp.code == 0) {
          this.submitStatus = 0
          this.utilMessage.success(resp.msg)
          this.form = global.utils.jsonClone(resp.data)
          this.snMergeNew = null
          this.form.locationId = null
          this.form.locationName = null
          this.form.locationIdcode = null
        }
        this.utilVue.loadHide()
      })
    },
    //扩展加工按钮
    handleExtraButtonClick(para) {
      if (para.button.key == 'process') {
        this.handleProcess()
      }
    },
    handleReset() {
      this.utilMessage.confirm('您正在重置表单，是否继续?', () => {
        this.initData()
        this.fetchData()
      })
    },
    //设置选择状态
    setCheckedRecores() {
      if (!this.$refs.childProcessStock || this.submitStatus == 1) {
        return
      }
      // this.autoFlagCheck = true
      this.$refs.childProcessStock.ocSetShowCheckBox(true)
      let processRows = this.$refs.childProcessStock.getRows()
      if (processRows == 0) {
        return
      }
      processRows.forEach(row => {
        this.$refs.childProcessStock.ocSetCheckboxRow(row, false)
      })

      let checkNum = Math.floor(this.form.processRate / this.form.skuQty)
      checkNum > 0 && processRows.slice(0, checkNum).forEach(row => { //自动选择好需要的数量
        this.$refs.childProcessStock.ocSetCheckboxRow(row, true)
      })
    }
  },
}
</script>
<style lang="scss" scoped>
  .container {
    height: 100%;
  }

  .button-box-top {
    padding: 10px 20px 20px 30px;
    button {
      margin-right: 10px;
    }
  }

  .form-right {
    background-color: #fff;
  }

  .el-button {
    margin-left: 20px !important
  }

  /deep/ .edit-down-pulldown {
    width: 50px !important;
  }

  /deep/ .root-box {
    padding-right: 0 !important;
  }

  .tag-name {
    margin-left: 2px;
    font-size: 20px;
    color: #d54941;
    vertical-align: middle;
  }
</style>
